/*
 * 文件名：Tools.java
 * 版权：Copyright by www.suyinchina.com
 * 描述：
 * 修改人：WS
 * 修改时间：2015年3月25日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.xd.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Logger;

import static org.apache.commons.codec.CharEncoding.UTF_8;

public class Tools
{

    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
    private static final String AESTYPE ="AES/ECB/NoPadding";

    /**
     * 检测对象是否不为空(null,"","null")
     * @param obj
     * @return 不为空则返回true，否则返回false
     */
    public static boolean notEmpty(Object obj)
    {
    	if(null == obj || "".equals(obj) || "null".equals(obj))
            return false;
        return true;
    }

    /**
     * 检测字符串是否为空(null,"","null")
     * @param s
     * @return 为空则返回true，不否则返回false
     */
    public static boolean isEmpty(String s)
    {
        return s == null || "".equals(s) || "null".equals(s);
    }

    /**
     * 字符串转换为字符串数组
     * @param str 字符串
     * @param splitRegex 分隔符
     * @return
     */
    public static String[] str2StrArray(String str, String splitRegex)
    {
        if (isEmpty(str))
        {
            return null;
        }
        return str.split(splitRegex);
    }

    /**
     * 用默认的分隔符(,)将字符串转换为字符串数组
     * @param str   字符串
     * @return
     */
    public static String[] str2StrArray(String str)
    {
        return str2StrArray(str, ",\\s*");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，日期转字符串
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date2Str(Date date)
    {
        return date2Str(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 按照yyyy-MM-dd HH:mm:ss的格式，字符串转日期
     * @param date
     * @return
     */
    public static Date str2Date(String date)
    {
        if (notEmpty(date))
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try
            {
                return sdf.parse(date);
            }
            catch (ParseException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return new Date();
        }
        else
        {
            return null;
        }
    }

    /**
     * 按照参数format的格式，日期转字符串
     * @param date
     * @param format
     * @return
     */
    public static String date2Str(Date date, String format)
    {
        if (date != null)
        {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        }
        else
        {
            return "";
        }
    }
    
    /**
     * 字符串为null的返回""
     * @param
     * @param
     * @return
     */
    public static String nullToEmpty(String str)
    {
        if(isEmpty(str)){
            return "";
        }
        return str;
    }
    public static String getTime(String dateTime){
        String returnTime=dateTime.substring(0,10);
        String nowDate=new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date());
        long leftTime=(Tools.str2Date(dateTime).getTime())-Tools.str2Date(nowDate).getTime();
        if(Math.floor(leftTime/1000/60/60)<=24){
            int h=Integer.parseInt(dateTime.substring(11,13));
            if(h==0){
                returnTime="今天23:59"; 
            }
            else{
                returnTime="今天"+dateTime.substring(11,16);
            }
        }
        return returnTime;
    }
    
    /*时间比大小  -1为过期*/
    public static int timeCompare(String t1){
        int result = 0 ;
        if(null != t1){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar c1=Calendar.getInstance();
            Calendar c2=Calendar.getInstance();
            try {
                c1.setTime(formatter.parse(t1));
                c2.setTime(formatter.parse(getCurrentTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            result=c1.compareTo(c2);
        }
        return result;
     }
    
    public static String getCurrentTime(){
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
    /**
     * 获取uuid
     * @return
     */
    public static String getUUID(){
    	String uuid=UUID.randomUUID().toString();
    	return uuid.replaceAll("-", "");
    }
    
    /**
     * 获取随机数
     */
    public static String getRandomNum(Integer digit){
    	String result = "";
        Random random = new Random();
        for (int i = 0; i < digit; i++) {
			result += Math.abs(random.nextInt(10));
		}
        return result;
    }
    
    /**
     * Description: 获取编号
     * 
     * @return 
     * @see 
     */
    public static String  getCode(){
        Random random = new Random();
        String num =String.valueOf(random.nextInt(999999));
        SimpleDateFormat  fileDate = new SimpleDateFormat("yyMMDDMMSS");
        String newFileName_dt=fileDate.format(new Date());
        return newFileName_dt+num;
    }


    /**
     * 对给定的字符串进行base64解码操作
     */
    public static String decodeDatabase64(String inputData) {
        try {
            if (null == inputData) {
                return null;
            }
            return new String(Base64.decodeBase64(inputData.getBytes(UTF_8)), UTF_8);
        } catch (UnsupportedEncodingException e) {

        }

        return null;
    }

    /**
     * 对给定的字符串进行base64加密操作
     */
    public static String encodeDatabase64(String inputData) {
        try {
            if (null == inputData) {
                return null;
            }
            return new String(Base64.encodeBase64(inputData.getBytes(UTF_8)), UTF_8);
        } catch (UnsupportedEncodingException e) {
        }

        return null;
    }


    /**
     * md5
     * @param str
     * @return
     */
    public static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            str = buf.toString();
        } catch (Exception e) {
            e.printStackTrace();

        }
        return str;
    }





    private Key initKeyForAES(String key) throws NoSuchAlgorithmException {
        if (null == key || key.length() == 0) {
            throw new NullPointerException("key not is null");
        }
        SecretKeySpec key2 = null;
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(key.getBytes());
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            key2 = new SecretKeySpec(enCodeFormat, "AES");
        } catch (NoSuchAlgorithmException ex) {
            throw new NoSuchAlgorithmException();
        }
        return key2;

    }



public static String AES_Encrypt(String keyStr, String plainText) {
    byte[] encrypt = null;
    try{
        Key key = generateKey(keyStr);
        Cipher cipher = Cipher.getInstance(AESTYPE);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        encrypt = cipher.doFinal(plainText.getBytes());
    }catch(Exception e){
        e.printStackTrace();
    }
    return new String(Base64.encodeBase64(encrypt));
}

    public static String AES_Decrypt(String keyStr, String encryptData) {
        byte[] decrypt = null;
        try{
            Key key = generateKey(keyStr);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            decrypt = cipher.doFinal(Base64.decodeBase64(encryptData));
        }catch(Exception e){
            e.printStackTrace();
        }
        return new String(decrypt).trim();
    }

    private static Key generateKey(String key)throws Exception{
        try{
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
            return keySpec;
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }

    }

}
